<style scoped>
@import 'vuepc.css';
</style>

<template>
  <el-dialog
    title="节点组件配置"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :fullscreen="fullScreen"
    width="80%"
    :before-close="clearForm">
    <!-- 自定义title -->
    <div slot="title" class="header-title">
      <span class="title-text">节点组件配置</span>
      <el-button style="float: right;margin-right: 20px;margin-top: -10px" size="=mini" type="text" icon="el-icon-full-screen" @click="fullScreen = !fullScreen"></el-button>
    </div>
    <el-form
      :label-position="labelPosition"
      label-width="80px"
      :model="saveData"
      :rules="rules"
      ref="ruleForm"
    >
      <el-form-item label="系统" prop="systemUuid">
        <el-select filterable
                   :disabled="saveData.id !==''"
                   v-model="saveData.systemUuid"
                   @change="refreshNodeOptions"
                   placeholder="请选择系统">
          <el-option
            v-for="item in systemOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="节点" prop="systemUuid">
        <el-select filterable :disabled="saveData.id !=='' || saveData.systemUuid === ''"
                   v-model="saveData.nodeUuid" placeholder="请选择节点">
          <el-option
            v-for="item in nodeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="组件名称" prop="nodeVueName">
        <el-input :disabled="saveData.id !==''" v-model="saveData.nodeVueName"></el-input>
      </el-form-item>
      <el-form-item label="组件Key" prop="nodeVueKey">
        <el-input :disabled=" saveData.id !==''" v-model="saveData.nodeVueKey"></el-input>
      </el-form-item>
      <el-form-item label="组件类型" prop="nodeVueType">
        <el-select filterable
                   v-model="saveData.nodeVueType"
                   placeholder="请选择组件类型">
          <el-option
            v-for="item in nodeVueTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上下文" prop="pluginContext">
        <el-input v-model="pluginContext" type="textarea" :rows="4" placeholder="组件上下文数据(测试)"></el-input>
      </el-form-item>
      <el-form-item label="组件代码" prop="nodeVueCode">
        <!--        <el-input-->
        <!--          type="textarea"-->
        <!--          :rows="30"-->
        <!--          placeholder="组件代码"-->
        <!--          @input="vueCodeChange"-->
        <!--          v-model="saveData.nodeVueCode">-->
        <!--        </el-input>-->
        <!--        <codemirror-->
        <!--          v-model="saveData.nodeVueCode"-->
        <!--          :options="cmOption" class="code-mirror"-->
        <!--          @ready="onCmReady3"-->
        <!--          @focus="onCmFocus"-->
        <!--          @input="vueCodeChange"-->
        <!--          ref="myCmGenerate"></codemirror>-->
        <codemirror
          ref="myCm"
          :value="saveData.nodeVueCode"
          :options="cmOption"
          @changes="vueCodeChange"
          @ready="onCmReady"
          class="code"
        ></codemirror>
      </el-form-item>
      <el-form-item label="组件预览">
        <vuep ref="vuep" style="line-height: 15px" :template="saveData.nodeVueCode"></vuep>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
    <el-button @click="clearForm">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </span>
  </el-dialog>
</template>
<script>

import {nodeSelector, nodeVueType, systemSelector} from "@/api/loadSelectorApi";
import {nodeStyleSave} from "@/api/nodeStyle";
import {nodeVueLoad, nodeVueSave, remoteValidateNodeVueName, remoteValidatesNodeVueKey} from "@/api/nodeVue";

import 'codemirror/mode/vue/vue.js'
import 'codemirror/theme/eclipse.css'
import 'codemirror/addon/selection/active-line.js'
import 'codemirror/addon/edit/closebrackets.js'
import 'codemirror/addon/fold/comment-fold.js';

import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/show-hint.js'
import 'codemirror/addon/hint/html-hint'
import 'codemirror/addon/hint/css-hint'
import 'codemirror/addon/hint/javascript-hint'
import 'codemirror/addon/hint/anyword-hint'

import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/foldcode'
import 'codemirror/addon/fold/foldgutter'
import 'codemirror/addon/fold/brace-fold'
import 'codemirror/addon/fold/comment-fold'
import 'codemirror/addon/fold/markdown-fold'
import 'codemirror/addon/fold/xml-fold'
import 'codemirror/addon/fold/indent-fold'

import 'codemirror/addon/search/match-highlighter'

import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/edit/closebrackets'

export default {
  name: "nodeVueForm",
  filters: {},
  components: {},
  data() {
    const validateName = async (rule, value, callback) => {
      if (this.saveData.id) {
        callback()
      }
      let systemUuid = this.saveData.systemUuid;

      if (systemUuid === '') {
        callback(new Error("请先选择节点组件所属系统"))
      }

      let ret = await remoteValidateNodeVueName(systemUuid, value);
      if (ret.data.result) {
        callback()
      } else {
        callback(new Error("节点组件名字不能重复"))
      }
    };
    const validateKey = async (rule, value, callback) => {
      if (this.saveData.id) {
        callback()
      }
      let systemUuid = this.saveData.systemUuid;
      if (systemUuid === '') {
        callback(new Error("请先选择节点组件所属系统"))
      }
      let ret = await remoteValidatesNodeVueKey(systemUuid, value);
      if (ret.data.result) {
        callback()
      } else {
        callback(new Error("节点组件Key不能重复"))
      }
    };
    return {
      cmOption: {
        tabSize: 2,
        styleActiveLine: true,
        lineNumbers: true,
        line: true,
        mode: 'text/x-vue',
        // extraKeys: {"Ctrl": "autocomplete"},
        lineWrapping: false,
        theme: 'eclipse',
        undoDepth: 200,
        gutters: [
          "CodeMirror-lint-markers",
          "CodeMirror-linenumbers",
          "CodeMirror-foldgutter"
        ],
        foldGutter:true,
        highlightSelectionMatches: {
          minChars: 2,
          trim: true,
          style: "matchhighlight",
          showToken: false
        },
        autoCloseBrackets: true, // 自动闭合符号
        matchBrackets: true, // 在光标点击紧挨{、]括号左、右侧时，自动突出显示匹配的括号 }、]
      },

      labelPosition: 'right',
      dialogVisible: false,
      fullScreen: false,
      saveData: {
        id: '',
        systemUuid: '',
        nodeUuid: '',
        nodeVueName: '',
        nodeVueKey: '',
        nodeVueCode: '',
        nodeVueType: '',
      },
      rules: {
        nodeVueName: [
          {required: true, message: '此项必填', trigger: 'blur'},
          {validator: validateName, trigger: 'blur'}
        ],
        nodeVueKey: [
          {required: true, message: '此项必填', trigger: 'blur'},
          {validator: validateKey, trigger: 'blur'}
        ],
        nodeVueCode: [
          {required: true, message: '此项必填', trigger: 'blur'}
        ],
        systemUuid: [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
        nodeUuid: [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
        nodeVueType: [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
      },
      systemOptions: [],
      nodeVueTypeOptions: [],
      nodeOptions: [],
      pluginContext: ''
    }
  },
  async created() {
    this.systemOptions = await systemSelector();
    this.nodeVueTypeOptions = await nodeVueType();
  },
  mounted() {
  },
  methods: {
    async load(data) {
      let vm = this
      if (data) {
        vm.saveData = vm.$cloneObj(data)
        vm.pluginContext = vm.saveData.pluginContext
      } else {
        const ret = await nodeVueLoad();
        if (ret.ok) {
          vm.saveData.nodeVueCode = ret.data.nodeVueCode
        } else {
          vm.saveData.nodeVueCode = {}
        }
      }
      vm.dialogVisible = true
      vm.$nextTick(function () {
        vm.$refs.vuep.content = vm.saveData.nodeVueCode
      })
    },
    save() {
      let vm = this
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          vm.saveData.pluginContext = vm.pluginContext
          await vm.doSave(this.saveData)
        }
      })
    },
    async doSave(saveData) {
      let vm = this
      vm.saveData.nodeVueCode = vm.$refs.vuep.content

      let ret = await nodeVueSave(saveData);
      if (ret.ok) {
        vm.$message({type: 'success', message: '保存成功'});
      } else {
        vm.$message({type: 'error', message: '保存失败：' + ret.message});
      }
      vm.clearForm()
      vm.$parent.query()
    },
    vueCodeChange(cm) {
      let vm = this
      let value = cm.getValue();
      vm.saveData.nodeVueCode = value
      vm.$refs.vuep.content = value
    },
    async doDeletedSave(saveData) {
      const vm = this
      const ret = await nodeStyleSave(saveData);
      if (ret.ok) {
        vm.$message({type: 'success', message: '保存成功'});
      } else {
        vm.$message({type: 'error', message: '保存失败：' + ret.message});
      }
      vm.clearForm()
      vm.$parent.query()
    },
    clearForm() {
      const vm = this
      try {
        vm.saveData = {
          id: '',
          systemUuid: '',
          nodeUuid: '',
          nodeVueName: '',
          nodeVueKey: '',
          nodeVueCode: '',
          nodeVueType: '',
        }
        vm.pluginContext = ''
        vm.fullScreen = false
        vm.$refs['ruleForm'].resetFields()
      } catch (e) {
        console.log(e)
      }
      vm.dialogVisible = false
    },
    async refreshNodeOptions() {
      let vm = this
      vm.saveData.nodeUuid = ''
      vm.nodeOptions = []
      if (vm.saveData.systemUuid !== '') {
        vm.nodeOptions = await nodeSelector(vm.saveData.systemUuid)
      }
    },
    onCmReady(cm) {
      // this.$refs.newCm.codemirror.setSize("-webkit-fill-available", "auto")
      // 这里的 cm 对象就是 codemirror 对象，等于 this.$refs.myCm.codemirror
      cm.on("inputRead", (cm, obj) => {
        if (obj.text && obj.text.length > 0) {
          let c = obj.text[0].charAt(obj.text[0].length - 1)
          if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
            cm.showHint({completeSingle: false})
          }
        }
      })
    }
  }
}
</script>
